package com.talent.service.auth.service.security;


import com.talent.model.entity.sys.SysUser;
import com.talent.service.auth.constant.LoginConstant;
import com.talent.service.auth.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName：UserServiceImpl
 * @Author: hszhou
 * @Date: 2025/2/7 9:21
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final ISysUserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String loginType = requestAttributes.getRequest().getParameter("login_type");
        if(StringUtils.isEmpty(loginType)){
            throw new AuthenticationServiceException("登陆类型不能为空");
        }
        switch (loginType){
            case LoginConstant.LOGIN_ADMIN_TYPE:
                return loadSysUserByUsername(username);
            case LoginConstant.LOGIN_MEMBER_TYPE:
                return loadMemberUserByUsername(username);
            default:
                throw new AuthenticationServiceException("暂不支持登陆方式");
        }

    }

    /**
     * 会员登陆
     * @param username
     * @return
     */

    private UserDetails loadMemberUserByUsername(String username) {
        return null;
    }

    /**
     * 后台人员登录
     * @param username
     * @return
     */

    private UserDetails loadSysUserByUsername(String username) {
        SysUser user = userService.selectUserByUsername(username);
        if(Objects.isNull(user)){
            throw new UsernameNotFoundException(username);
        }
        List<SimpleGrantedAuthority> permission =
                userService.getPermission(user.getId()).stream()
                        .distinct()
                        .map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return new User(user.getId().toString(),
                user.getPassword(),
                true,
                true,
                true,
                true,
                permission);
    }
}
